package com.deductive.netty.websocket.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class WebSocketPushService {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketPushService.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 向指定用户推送消息
     *
     * @param userId  用户ID
     * @param message 要发送的消息
     */
    public void pushToUser(String userId, Object message) {
        Channel channel = NettyConnectionManager.getChannel(userId);
        if (channel != null && channel.isActive()) {
            try {
                String jsonMessage = objectMapper.writeValueAsString(message);
                channel.writeAndFlush(new TextWebSocketFrame(jsonMessage));
                logger.info("已向用户 {} 推送消息: {}", userId, jsonMessage);
            } catch (JsonProcessingException e) {
                logger.error("为用户 {} 序列化消息失败", userId, e);
            }
        } else {
            logger.warn("用户 {} 未连接或通道未激活", userId);
        }
    }

    /**
     * 向所有连接的用户推送消息
     *
     * @param message 要发送的消息
     */
    public void pushToAll(Object message) {
        try {
            String jsonMessage = objectMapper.writeValueAsString(message);
            ChannelGroup channels = NettyConnectionManager.getChannels();
            channels.writeAndFlush(new TextWebSocketFrame(jsonMessage));
            logger.info("已向所有用户推送消息: {}", jsonMessage);
        } catch (JsonProcessingException e) {
            logger.error("为广播序列化消息失败", e);
        }
    }

    /**
     * 广播用户上线的消息
     *
     * @param userId 上线的用户ID
     */
    public void broadcastUserOnline(String userId) {
        java.util.Map<String, Object> payload = new java.util.HashMap<>();
        payload.put("userId", userId);

        java.util.Map<String, Object> message = new java.util.HashMap<>();
        message.put("type", "USER_ONLINE");
        message.put("payload", payload);

        pushToAll(message);
        logger.info("已广播用户 {} 上线消息", userId);
    }

    /**
     * 广播用户下线的消息
     *
     * @param userId 下线的用户ID
     */
    public void broadcastUserOffline(String userId) {
        java.util.Map<String, Object> payload = new java.util.HashMap<>();
        payload.put("userId", userId);

        java.util.Map<String, Object> message = new java.util.HashMap<>();
        message.put("type", "USER_OFFLINE");
        message.put("payload", payload);

        pushToAll(message);
        logger.info("已广播用户 {} 下线消息", userId);
    }
}